import 'dart:math';

import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_page/cartoon_business/widget/acg_expand_text.dart';
import 'package:xvideos/hj_page/home_business/tag/carrtoon_tag_page.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/widget/follow_button.dart';
import 'package:xvideos/tools_base/widget/keep_alive_widget.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../../../hj_utils/screen.dart';
import '../../../tools_base/loading/l_error_widget.dart';
import '../../../tools_base/loading/loading_center_widget.dart';
import '../../alert_business/video/share_video_dialog.dart';
import '../../hj_model/video_model.dart';
import 'cartoon_detail_logic.dart';
import 'cartoon_recommend_page.dart';
import 'widget/acg_source_manager.dart';

//acg详情页,小说和漫画 合并
class CartoonDetailPage extends StatefulWidget {
  final String id;
  final String? heroTag;
  const CartoonDetailPage({super.key, this.id = '', this.heroTag});

  @override
  State<CartoonDetailPage> createState() => _CartoonDetailPageState();
}

class _CartoonDetailPageState extends State<CartoonDetailPage> {
  late CartoonDetailLogic logic;
  late String tag;

  @override
  void initState() {
    super.initState();
    tag = widget.id + DateTime.now().millisecondsSinceEpoch.toString();
    logic = Get.put(CartoonDetailLogic(id: widget.id), tag: tag);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MultiProvider(
        providers: [ChangeNotifierProvider(create: (ctx) => logic.manager)],
        child: GetBuilder<CartoonDetailLogic>(
          tag: tag,
          builder: (_) {
            if (_.mediaInfo == null) return LoadingCenterWidget();
            if (_.mediaInfo?.id == null)
              return CErrorWidget(
                retryOnTap: () => _.loadData(),
              );
            return _buildContent(_);
          },
        ),
      ),
    );
  }

  _buildContent(CartoonDetailLogic _) {
    return Column(
      children: [
        Expanded(
            child: Stack(
          children: [
            ExtendedNestedScrollView(
              controller: _.scrollController,
              onlyOneScrollInBody: true,
              headerSliverBuilder: (context, innerBoxIsScrolled) {
                return [
                  SliverToBoxAdapter(child: _buildImgHeader(_)), //header
                  SliverToBoxAdapter(child: _buildMenu(_)), //目录
                ];
              },
              body: Column(
                children: [
                  //推荐
                  Expanded(
                    child: CartoonRecommendPage(mediaId: widget.id).keepAlive,
                  ),
                ],
              ),
            ),
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: _buildTopHeader(),
            ),
          ],
        )),
        Padding(
          padding: EdgeInsets.symmetric(vertical: 10),
          child: Row(
            children: [
              16.sizeBoxW,
              if (_.isCartoonType) ...[
                Consumer<ACGSourceManager>(
                  builder: (context, manager, child) {
                    bool liked = manager.mediaInfo?.mediaStatus?.hasLiked == true;
                    return InkWell(
                      onTap: () => manager.onLikeAction(),
                      child: Container(
                          width: 108,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(3),
                          ),
                          height: 44,
                          alignment: Alignment.center,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                liked ? 'acg_like_sel.png'.acgImgPath : 'acg_like_nor.png'.acgImgPath,
                                width: 16,
                              ),
                              10.sizeBoxW,
                              Text(
                                '喜欢',
                                style: textStyle(16, Color(0xff3D3D3D), FontWeight.w500),
                              ),
                            ],
                          )),
                    );
                  },
                ),
                12.sizeBoxW,
              ],
              Expanded(
                child: InkWell(
                  onTap: () => _.play(),
                  child: Container(
                    decoration: BoxDecoration(
                      color: AppColors.actionRed,
                      borderRadius: BorderRadius.circular(3),
                    ),
                    height: 44,
                    alignment: Alignment.center,
                    child: Text(
                      '开始阅读',
                      style: textStyle(16, Colors.white, FontWeight.w500),
                    ),
                  ),
                ),
              ),
              16.sizeBoxW,
            ],
          ),
        ),
      ],
    );
  }

  _buildImgHeader(CartoonDetailLogic _) {
    return Stack(
      children: [
        //背景图
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: NetworkImageLoader(
            imageUrl: '${_.mediaInfo?.verticalCover ?? ""}',
            borderRadius: 0,
            height: 350,
            alignment: Alignment.topCenter,
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            (10 + screen.paddingTop).sizeBoxH,
            Row(
              children: [
                _buildBackView(),
                Spacer(),
                _buildCollAction(),
                12.sizeBoxW,
                _builShareView(),
              ],
            ).paddingSymmetric(horizontal: 16),
            154.sizeBoxH,
            Text(
              '${_.mediaInfo?.title ?? ""}',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.w900,
                fontFamily: 'Roboto',
              ),
            ).paddingSymmetric(horizontal: 16),
            12.sizeBoxH,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(
                color: Color(0xff1A1A1A),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20),
                  topRight: Radius.circular(20),
                ),
              ),
              child: Column(
                children: [
                  18.sizeBoxH,
                  Row(
                    children: [
                      _buildStateItem(
                        'view_count.png'.communityPath,
                        logic.mediaInfo?.countBrowse?.humanizeFormat ?? '',
                      ),
                      12.sizeBoxW,
                      _buildSpe(),
                      12.sizeBoxW,
                      GetBuilder<CartoonDetailLogic>(
                        tag: tag,
                        id: 'status',
                        builder: (_) => _buildStateItem(
                          _.manager.mediaInfo?.mediaStatus?.hasLiked == true
                              ? 'community_thumb_sel.png'.communityPath
                              : 'like_count.png'.communityPath,
                          logic.manager.mediaInfo?.countLike?.humanizeFormat ?? '',
                        ),
                      ),
                      20.sizeBoxW,
                      _buildSpe(),
                      12.sizeBoxW,
                      // 0:会员 1:金币购买 2:免费
                      if (logic.mediaInfo?.permission == 0) ...[
                        Text(
                          'VIP',
                          style: textStyle(12, Color(0xff989898), FontWeight.w400),
                        ),
                      ] else if (logic.mediaInfo?.permission == 1) ...[
                        Text(
                          '${logic.mediaInfo?.price ?? 0}金币',
                          style: textStyle(12, Color(0xff989898), FontWeight.w400),
                        ),
                      ],
                    ],
                  ),
                  //详情
                  if (logic.mediaInfo?.summary?.isNotEmpty == true) ...[
                    12.sizeBoxH,
                    Padding(
                      padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
                      child: AcgShowMoreTextWidget(
                        summary: logic.mediaInfo?.summary ?? '',
                        maxWidth: Get.width - 10,
                      ),
                    )
                  ],
                  //标签
                  if ((_.mediaInfo?.tagDetails?.length ?? 0) != 0) ...[
                    12.sizeBoxH,
                    Container(
                      height: 26,
                      child: ListView.separated(
                        separatorBuilder: (context, index) => 6.sizeBoxW,
                        itemCount: _.mediaInfo?.tagDetails?.length ?? 0,
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (context, index) {
                          TagsBean? tag = _.mediaInfo?.tagDetails?[index];
                          return InkWell(
                            onTap: () {
                              Get.to(CartoonTagPage(
                                title: tag?.name ?? '',
                                sId: tag?.id ?? '',
                              ));
                            },
                            child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 8),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(color: Colors.white.withOpacity(.05), borderRadius: BorderRadius.circular(3)),
                                height: 26,
                                child: Text(
                                  '${tag?.name ?? ''}',
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(.45),
                                    fontSize: 12,
                                    fontWeight: FontWeight.w400,
                                  ),
                                )),
                          );
                        },
                      ),
                    ),
                    12.sizeBoxH,
                  ],
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  _buildSpe() {
    return Container(
      color: Colors.white.withOpacity(.1),
      width: 0.5,
      height: 18,
    );
  }

  _buildStateItem(String img, String name) {
    return Row(
      children: [
        Image.asset(img, width: 16),
        4.sizeBoxW,
        Text(
          name,
          style: textStyle(12, Color(0xff989898), FontWeight.w400),
        )
      ],
    );
  }

  _buildMenu(CartoonDetailLogic _) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          18.sizeBoxH,
          Row(
            children: [
              Text(
                _.isCartoonType ? '选集' : '共${logic.mediaInfo?.totalEpisode ?? 0}${logic.mediaInfo?.unit}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Spacer(),
              Row(
                children: [
                  InkWell(
                    onTap: logic.onMenuAction,
                    child: Text(
                      _.isCartoonType ? '全${logic.mediaInfo?.totalEpisode ?? 0}${logic.mediaInfo?.unit}' : '目录',
                      style: TextStyle(
                        color: Color(0xFFA7A7A7),
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  2.sizeBoxW,
                  Image.asset(
                    'arrow_right_grey.webp'.commonImgPath,
                    color: Color(0xff989898),
                    width: 24,
                  )
                ],
              )
            ],
          ),
          18.sizeBoxH,
          Consumer<ACGSourceManager>(
            builder: (context, provider, child) {
              return ListView.builder(
                padding: EdgeInsets.zero,
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () => logic.changeEpisode(index, false),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: _.isCartoonType ? 6 : 12),
                      child: Text(
                        '第${provider.allEpisodes[index].episodeNumber ?? ''}${provider.mediaInfo?.unit}${_.isCartoonType ? '' : '  ${provider.allEpisodes[index].name}'}',
                        style: textStyle(
                          16,
                          provider.index == index ? Colors.white.withOpacity(.9) : Colors.white.withOpacity(.45),
                          provider.index == index ? FontWeight.w500 : FontWeight.w400,
                        ),
                      ),
                    ),
                  );
                },
                itemCount: min(4, provider.allEpisodes.length),
              );
            },
          ),
          18.sizeBoxH,
          if (_.isCartoonType) 0.5.line,
          18.sizeBoxH,
          Text(
            '相似作品',
            style: textStyle(
              18,
              Colors.white.withOpacity(.9),
              FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  _buildBackView() {
    return InkWell(
      child: Image.asset(
        'back_circle_grey.png'.commonImgPath,
        width: 24,
      ),
      onTap: () => Get.back(),
    );
  }

  _builShareView() {
    return InkWell(
      onTap: () {
        Get.dialog(
          ShareVideoDialog(
            isCoverV: true,
            videoModel: VideoModel()
              ..id = logic.mediaInfo?.id
              ..cover = logic.mediaInfo?.coverH,
          ),
        );
      },
      child: Image.asset("acg_share.png".acgImgPath, width: 24),
    );
  }

  _buildTopHeader() {
    return GetBuilder<CartoonDetailLogic>(
      tag: tag,
      id: 'header',
      builder: (_) {
        return Offstage(
          offstage: logic.showHeader,
          child: Container(
            padding: EdgeInsets.only(left: 16, right: 16, top: screen.paddingTop),
            height: 44 + screen.paddingTop,
            color: Color(0xff0E141E),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () => Get.back(),
                  child: Icon(Icons.arrow_back_ios, size: 24, color: Colors.white),
                ),
                8.sizeBoxW,
                Expanded(
                  child: Text(
                    logic.mediaInfo?.title ?? '',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Colors.white),
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                _buildCollAction(),
                12.sizeBoxW,
                _builShareView(),
              ],
            ),
          ),
        );
      },
    );
  }

  _buildCollAction() {
    return Consumer<ACGSourceManager>(
      builder: (context, mananger, child) {
        bool col = mananger.mediaInfo?.mediaStatus?.hasCollected ?? false;
        return FollowButton(
          mediaId: mananger.mediaInfo?.id ?? '',
          isFollow: col,
          followType: FollowEnum.cartoon,
          successsAction: (isSuccess) {
            context.read<ACGSourceManager>().updateLikeState(isSuccess);
            mananger.updateLikeState(isSuccess);
            if (isSuccess) {
              showToast('收藏成功');
            }
          },
        );
      },
    );
  }
}
